#!/usr/bin/env python
import sys
import socket
import random
import yaml
from OpenSSL.crypto import dump_certificate, dump_privatekey, FILETYPE_PEM, PKey, TYPE_RSA, X509

if len(sys.argv) < 2:
    print 'Usage: ajenti-ssl-gen <hostname> [-f]'
    sys.exit(1)

host = sys.argv[1]
etcdir = '/etc/ajenti'
certificate_path = '%s/ajenti.pem' % etcdir
config_path = '%s/config.yml' % etcdir

config = yaml.load(open(config_path))

if len(sys.argv) == 2:
    if config['ssl']['certificate']:
        print ':: SSL is already configured'
        sys.exit(1)

key = PKey()
key.generate_key(TYPE_RSA, 4096)
cert = X509()
cert.get_subject().countryName = 'NA'
cert.get_subject().organizationName = socket.gethostname()
cert.get_subject().commonName = 'ajenti'
cert.set_pubkey(key)
cert.set_serial_number(random.getrandbits(8 * 20))
cert.gmtime_adj_notBefore(0)
cert.gmtime_adj_notAfter(10 * 365 * 24 * 60 * 60)
cert.set_issuer(cert.get_subject())
cert.sign(key, 'sha1')


with open(certificate_path, 'w') as f:
    f.write(dump_privatekey(FILETYPE_PEM, key))
    f.write(dump_certificate(FILETYPE_PEM, cert))


config['ssl']['enable'] = True
config['ssl']['certificate'] = certificate_path
open(config_path, 'w').write(
    yaml.safe_dump(config, default_flow_style=False, encoding='utf-8', allow_unicode=True)
)
